<!--全部短信：通过搜索条件  查询全部短信-->
<template>
  <div class="smsAll">
    <affix :label="$t('sms.allSmsSearch')"></affix>
    <!--搜索条件 start==================================-->
    <el-form :model="ruleForm" ref="ruleForm" class="demo-ruleForm">
    <el-row>
      <div class="part">
        <span class="demonstration">{{$t('sms.timeScope')}}：</span>
        <el-date-picker size="mini" :id="['f1','f2']"
          class="choose-date"
          v-model="ruleForm.date"
          type="datetimerange"
          :picker-options="pickerOptions2"
          :placeholder="$t('sms.choTimeScope')"
          :editable="false"
          align="right">
        </el-date-picker>
      </div>
      <div class="part">
        <span class="demonstration">{{$t('sms.sendPhoneNum')}}：</span>
        <el-input size="mini" class="btn" v-model="ruleForm.phone"></el-input>
      </div>
      <div class="part">
        <span class="demonstration">{{$t('sms.smsState')}}：</span>
        <el-select size="mini" v-model="ruleForm.desc" :placeholder="$t('public.pleasePick')">
          <el-option
            :label="$t('public.all')"
            :value="''">
          </el-option>
          <el-option
            v-for="item in smsStatus"
            :label="smsSendingStatus === 'showAll' ? item.code_name : item.code_name_display"
            :value="item.code_value">
          </el-option>
        </el-select>
      </div>
      <div class="part">
        <span class="demonstration">{{$t('sms.smsSign')}}：</span>
        <el-select size="mini" class="choose-sign" v-model="ruleForm.region" :placeholder="$t('public.pleasePick')">
          <el-option
            :label="$t('public.all')"
            :value="''">
          </el-option>
          <el-option
            class="sms-all-sign-select-option"
            v-for="item in smsSign"
            :label="item.name"
            :value="item.subcode">
          </el-option>
        </el-select>
      </div>
      <div class="part">
        <span class="demonstration">{{$t('sms.sendAgents')}}：</span>
        <send-agent :sendTree="sendTree" ref="sendAgent"></send-agent>
      </div>
      <div class="submit">
        <el-button class="primary_btn report_excel_btn" @click.stop="resetForm">{{$t('public.reset')}}</el-button>
        <el-button type="primary" class="primary_btn" @click.stop="searchAllSms">{{$t('public.search2')}}</el-button>
      </div>
    </el-row>
    </el-form>
    <!--搜索条件  end================================-->
    <affix :label="$t('sms.allSearchList')"></affix>
    <div class="export-excel">
      <el-button type="primary" class="primary_btn" @click.stop="exportAllSmsExcelSearch">{{$t('sms.exportExcel')}}</el-button>
    </div>
    <div class="tables">
      <div class="deploy">
        <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
        <el-tooltip class="item" effect="dark" :content="$t('sms.smsWXTS', {smsSplitBaseNum: smsSplitBaseNum})" placement="right">
          <span class="te">{{$t('sms.searchIntroduce')}}</span>
        </el-tooltip>
          <Pagination
            class="fr"
            :small="true"
            :currentPage="currentPage"
            :count="count"
            @turnPage="handleCurrentChange"
            :totalPage="Math.ceil(count/pageSize)"
          >
          </Pagination>
      </div>
      <!--表格===============================================-->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="tableLoading" size="mini" border>
        <el-table-column prop="numHide" :label="$t('sms.sendPhoneNum')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="numAttribution" :label="$t('sms.sendLocation')" show-overflow-tooltip :render-header="renderHeader">
        </el-table-column>
        <el-table-column prop="agentsData" :label="$t('sms.sendAgents')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="submitTime" :label="$t('sms.sendTime')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="receiveTime" :label="$t('sms.receiveTime')" show-overflow-tooltip v-if="smsSendingStatus === 'showAll'" :render-header="renderHeader">
        </el-table-column>
        <el-table-column prop="m7StatusName" :label="$t('sms.smsState')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="splitCount" :label="$t('sms.splitNum')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="signDisplay" :label="$t('sms.sign')" show-overflow-tooltip>
      </el-table-column>
        <el-table-column prop="templateid_show" :label="$t('sms.temID')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="content" :label="$t('sms.content')" show-overflow-tooltip>
        </el-table-column>
        <el-table-column  :label="$t('sms.operate')" width="100">
          <template scope="scope">
            <el-button type="text" @click.stop="showSmsDetail(scope.$index, tableData)" size="small">{{$t('sms.searchToLook')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--表格==============================================================================-->
      <!--点击查看  dialog 短信详情    start  ===============================================-->
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('sms.smsDetailInfo')" :visible.sync="dialogSmsDetailVisible" width="50%">
        <el-row style="margin-bottom: 10px;">
          <el-col :span="3"><div>{{$t('sms.sendPhoneNum')}}:</div></el-col>
          <el-col :span="6"><div class="location">{{smsDetail.numHide}} <span :title="smsDetail.numAttribution" v-if="smsDetail.numAttribution" style="margin-left:3px;">({{smsDetail.numAttribution}})</span></div></el-col>
          <el-col :span="3"><div>{{$t('sms.sendTime')}}:</div></el-col>
          <el-col :span="4"><div>{{smsDetail.submitTime}}</div></el-col>
          <el-col :span="3"><div>{{$t('sms.splitNum')}}:</div></el-col>
          <el-col :span="5"><div>{{smsDetail.splitCount}}</div></el-col>
        </el-row>
        <el-row style="margin-bottom: 10px;">
          <el-col :span="3"><div>{{$t('public.callStatus')}}:</div></el-col>
          <el-col :span="6"><div>{{smsDetail.m7StatusName}}</div></el-col>
          <el-col :span="3"><div>{{$t('sms.sendAgents')}}:</div></el-col>
          <el-col :span="4"><div>{{smsDetail.agentsData}}</div></el-col>
          <el-col :span="3"><div>{{$t('sms.smsSign')}}:</div></el-col>
          <el-col :span="5"><div>{{smsDetail.signDisplay}}</div></el-col>
        </el-row>
        <el-row v-if="smsSendingStatus === 'showAll'" style="margin-bottom: 10px;">
          <el-col :span="3"><div>{{$t('sms.chanState')}}:</div></el-col>
          <el-col :span="21"><div>{{smsDetail.by_errordescription || '--'}}</div></el-col>
        </el-row>
        <el-row v-if="smsSendingStatus === 'showAll'" style="margin-bottom: 10px;">
          <el-col :span="3"><div>{{$t('sms.receiveTime')}}:</div></el-col>
          <el-col :span="21"><div>{{smsDetail.receiveTime || '--'}}</div></el-col>
        </el-row>
        <el-row style="margin-bottom: 10px;">
          <el-col :span="3"><div>{{$t('sms.smsCont')}}:</div></el-col>
          <el-col :span="21"><div>{{smsDetail.content}}</div></el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click.stop="dialogSmsDetailVisible = false">{{$t('sms.close')}}</el-button>
        </div>
      </el-dialog>
      <!--点击查看  dialog 短信详情    end   ===============================================-->
    </div>
  </div>
</template>
<script>
  import affix from '../../ui-modules/affix/Affix.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import sendAgent from './sendAgent'
  import {getCache, getFormatDateTime, checkHideTel, m7Language, deepClone} from '@/utils/m7Utils.js'
  export default {
    name: 'smsAll',
    props: {
      refresh: String
    },
    data () {
      return {
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        smsSplitBaseNum: 66,
        tableLoading: false,
//        分页数据相关
        pageSize: 10,
        currentPage: 1,
//        搜索条件数据双向绑定
        ruleForm: {
          region: '',
          date: '',
          phone: '',
          desc: '',
          createUser: ''
        },
//        搜索条件数据初始化
        smsStatus: [],
        smsSendingStatus: '',
        smsSign: [],
        agents: [],
//        查看短信详情开关
        dialogSmsDetailVisible: false,
//        短信详情信息初始化
        smsDetail: {},
        busTriggers: [],
        sendTree: [
          {id: 'all', label: this.$t('public.all')},
          {id: 'createUser', label: this.$t('public.agent'), children: []},
          {id: 'triggerId', label: this.$t('business.trigger'), children: []},
          {id: 'other', label: this.$t('questionnaire.otherStatus'), children: [{id: 'hangupSMS', label: this.$t('sms.hangupSMS'), type: 'createUser'}, {id: 'filterMessageSms', label: this.$t('sms.filterMessageSms'), type: 'createUser'}]}
        ]
      }
    },
    methods: {
//        点击查看
      showSmsDetail (index, rows) {
        this.dialogSmsDetailVisible = true
        this.smsDetail = rows[index]
      },
//      重置搜索条件
      resetForm () {
        for (let i in this.ruleForm) {
          this.ruleForm[i] = ''
        }
        this.$refs.sendAgent.reset()
      },
//     查询所有短信
      searchAllSms () {
        this.currentPage = 1
        this.searchSms()
      },
//      分页查询
      handleCurrentChange (val) {
        this.currentPage = val
        this.searchSms()
      },
//     查询短信
      searchSms () {
        this.tableLoading = true
        let data = {'pageSize': this.pageSize, 'page': this.currentPage}
        data.num = this.ruleForm.phone
        data.smsSendingStatus = this.smsSendingStatus
        data.m7Status = this.ruleForm.desc
        data.sign = this.ruleForm.region
        let sendData = this.$refs.sendAgent.sendData || {}
        Object.assign(data, sendData)
        let notifyTime = this.ruleForm.date
        if (notifyTime) {
          if (notifyTime[0]) {
            data.BEGIN_TIME = getFormatDateTime(notifyTime[0])
          }
          if (notifyTime[1]) {
            data.END_TIME = getFormatDateTime(notifyTime[1])
          }
        }
        this.$store.dispatch('queryAllSms', data).then(() => {
          this.tableLoading = false
        })
      },
//      导出Excel前 查询数量
      exportAllSmsExcelSearch () {
        let data = {'pageSize': this.pageSize, 'page': this.currentPage}
        data.num = this.ruleForm.phone
        data.smsSendingStatus = this.smsSendingStatus
        data.m7Status = this.ruleForm.desc
        data.sign = this.ruleForm.region
        let sendData = this.$refs.sendAgent.sendData || {}
        Object.assign(data, sendData)
        let notifyTime = this.ruleForm.date
        if (notifyTime) {
          if (notifyTime[0]) {
            data.BEGIN_TIME = getFormatDateTime(notifyTime[0])
          }
          if (notifyTime[1]) {
            data.END_TIME = getFormatDateTime(notifyTime[1])
          }
        }
        data.smsCountFlag = true
        this.$store.dispatch('queryAllSmsForExport', data).then((rep) => {
          if (rep.count < 100000) {
            this.exportAllSmsExcel()
          } else {
            this.$message.error(this.$t('sms.exportError'))
          }
        })
      },
      exportAllSmsExcel () {
        let data = {}
        let dataQuery = {}
        dataQuery.num = this.ruleForm.phone
        dataQuery.m7Status = this.ruleForm.desc
        dataQuery.sign = this.ruleForm.region
        let sendData = this.$refs.sendAgent.sendData || {}
        Object.assign(dataQuery, sendData)
        let notifyTime = this.ruleForm.date
        if (notifyTime) {
          if (notifyTime[0]) {
            dataQuery.BEGIN_TIME = getFormatDateTime(notifyTime[0])
          }
          if (notifyTime[1]) {
            dataQuery.END_TIME = getFormatDateTime(notifyTime[1])
          }
        }
        dataQuery.accountId = this.$store.state.session.account.account
        dataQuery.smsSendingStatus = this.smsSendingStatus
        dataQuery.DISPOSAL_AGENT = ''
        data.Method = 'exportAllSmsExcel'
        data.Query = dataQuery
        console.log(JSON.stringify(data))
        this.$store.dispatch('exportAllSms', data).then(() => {
        })
      },
       renderHeader (h,{column}) { // h即为cerateElement的简写，具体可看vue官方文档
         return h("div", [
          h("span", column.label + "  ", {
            align: "left"
          }),
          h(
            "el-popover",
            {
              props: {
                placement: "bottom-start",    // 一般 icon 处可添加浮层说明，浮层位置等属性
                trigger: "hover"
              },
              style:{
                color: '#459ae9',
              }
            },
            [
              h("p", column.property === 'receiveTime' ? this.$t('sms.receiveTimeTip') : this.$t('sms.locationPopover'), {
                class: "text-align: right; margin: 0"
              }),
              h("i", {                            // 生成 i 标签 ，添加icon 设置 样式，slot 必填
                class: "iconfont icon-wenzishuoming",
                slot: "reference"
              })
            ]
          )
        ]);
      }
    },
    computed: {
//        重构表单数据
      tableData () {
        let data = deepClone(this.$store.state.sms.allSms.list)
        for (var i in data) {
          let agentsId = data[i].createUser
          let triggerId = data[i].triggerId
          if (triggerId) {
            this.busTriggers.some((item) => {
              if (item.id === triggerId) {
                data[i].agentsData = item.label
                return true
              }
            })
          } else if (agentsId === 'hangupSMS') {
            data[i].agentsData = this.$t('sms.hangupSMS')
          } else if (agentsId === 'filterMessageSms') {
            data[i].agentsData = this.$t('sms.filterMessageSms')
          } else {
            data[i].agentsData = this.$store.getters.agents[agentsId] ? this.$store.getters.agents[agentsId].displayName : agentsId
          }
          data[i].numHide = checkHideTel(data[i].num, this.$store.state.session.user)
          data[i].m7StatusName = m7Language('globalChineseKey.' + data[i].m7StatusName, null, true) || data[i].m7StatusName
          if (!data[i].templateid && !data[i].templateNum) {
            data[i].templateid_show = ''
          } else {
            data[i].templateid_show = data[i].templateid || data[i].account + '_' + data[i].templateNum
          }
//          let smsStatusId = data[i].m7Status
//          let stateData = this.smsStatus
//          for (var j in stateData) {
//            if (stateData[j].code_value === smsStatusId) {
//              data[i].statusName = stateData[j].code_name
//            }
//          }
        }
        return data
      },
      count () {
        return this.$store.state.sms.allSms.count
      }
    },
    watch: {
      refresh (cur, old) {
        if (cur === 'all') {
          this.searchAllSms()
        }
      }
    },
    beforeMount () {
//    搜索条件预加载
      let p1 = this.$store.dispatch('getCache', {type: 'agents'})
      let p2 = this.$store.dispatch('getCache', {type: 'smsSign'})
      let p3 = this.$store.dispatch('queryAccountBusinessTrigger')
      Promise.all([p1, p2, p3]).then(([res1, res2, res3]) => {
        this.smsSplitBaseNum = this.$store.state.session.account.smsSplitBaseNum || 66
        let agents = this.$getCache('agents')
        this.agents = agents
        let smsSign = this.$getCache('smsSign')
        this.smsSign = smsSign
        if (this.$store.state.session.user.type === 'admin') {
          this.smsSendingStatus = 'showAll'
        } else {
          this.smsSendingStatus = this.$store.state.session.account.smsSendingStatus
          // 计费系统-产品-云客服/云电销/ 短信设置/ 短信发送状态设置
        }
        this.smsStatus = deepClone(getCache('smsStatus'))
        if (this.smsSendingStatus !== 'showAll') {
          this.smsStatus = this.smsStatus.filter(item => {
            if (item.code_value !== 'deliver' && item.code_value !== 'undeliver') {
              item.code_name = m7Language('globalChineseKey.' + item.code_name, null, true) || item.code_name
              item.code_name_display = m7Language('globalChineseKey.' + item.code_name_display, null, true) || item.code_name_display
              return item
            }
          })
        }
        // 生成发送座席树
        this.sendTree[1].children = res1.map((item) => {
          return {id: item._id, label: item.displayName, type: 'createUser'}
        })
        if (res3.success) {
          this.busTriggers = res3.list.map((item) => {
            let label = item.flowName + '-' + item.title
            return {id: item.triggerId, label, type: 'triggerId'}
          })
          this.sendTree[2].children = this.busTriggers
        }
//        this.loading = false
      })
    },
    components: {
      affix,
      Pagination,
      sendAgent
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  /deep/.icon-wenzishuoming
      color #459ae9
      font-size 16px
      font-weight normal
      cursor pointer
  .smsAll
    .location
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
    .el-pagination
      padding 0
    .tables
      padding 16px 20px 0 20px
      .deploy
        height 48px
        line-height 48px
        color $cf-gray1
        border 1px solid #e7e7eb
        border-bottom none
        padding-left 14px
        .fr
          padding-top 10px
          height 38px
        .tex
        .te
          cursor pointer
          &:hover
            color $c-main
        .set
          margin-right 10px
          position relative
          top 2px
        .iconfont
          font-size 10px
          color $c-main
        .tip
          display inline-block
          height 16px
          width 16px
          text-align center
          line-height 14px
          margin-right 10px
          position relative
          top -1px
        .icon-tixingweizhi
          border 1px solid $c-main
          display inline-block
          height 16px
          width 16px
          text-align center
          line-height 14px
          position relative
          top -1px
          border-radius 50%
    .ui-affix
      padding-bottom 0
    .submit
      text-align right
      margin 20px 0
    .el-input
      width inherit
      width 194px
    .part
      margin-bottom 20px
      display inline-block
    .choose-date
    .choose-sign
      width 360px
    .demonstration
      margin-right 10px
      display inline-block
      min-width 88px
      text-align right
      margin-left 20px
      color $cf-gray1
    .title
      color $cf-gray1
      margin 20px 0 18px 0
      font-weight normal
      position relative
      .sign
        position relative
        width 12px
        height 12px
        background #7ccdd1
        display inline-block
        z-index 3
      .text
        position relative
        display inline-block
        padding 0 8px 0 10px
        background $cf-white
        z-index 3
      &:after
        content ""
        display inline-block
        width 100%
        left 0
        border-bottom 1px dashed $cf-level2
        position absolute
        top 12px
    .export-excel
      text-align right
  .sms-all-sign-select-option
  .sms-all-agents-select-option
    max-width 360px
    height auto
    word-wrap break-word
    white-space normal
  .sms-all-agents-select-option
    max-width 194px
</style>
